package com.example.SocketSelectorStudy;

import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

/**
 * 客户端
 */
public class MySelectorClient {

    public static ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
    public static ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    static Random random = new Random();

    public static void main(String[] args) {
        try {
            run(8888);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void run(int connectPort) throws IOException, InterruptedException {
        //创建连接到server的管道
        SocketChannel socketChannel = SocketChannel.open();
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress(connectPort));
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                SocketChannel server = (SocketChannel) selectionKey.channel();
                if(selectionKey.isConnectable()) {
                    if (server.isConnectionPending()) {
                        server.finishConnect();
                        selectionKey.interestOps(SelectionKey.OP_WRITE);
                    }
                    System.out.println("connect to a server, ready to write.");
                } else if (selectionKey.isWritable()) {
                    System.out.println("please input something.");
                    Scanner scanner = new Scanner(System.in);
                    String sendString = scanner.next();
                    /*String sendString = "朱乾力";

                    Thread.sleep( random.nextInt(1000)+500);*/
                    sendBuffer.flip();
                    sendBuffer = ByteBuffer.wrap(sendString.getBytes());
                    server.write(sendBuffer);
                    selectionKey.interestOps(SelectionKey.OP_READ);
                } else if(selectionKey.isReadable()){
                    readBuffer.clear();
                    server.read(readBuffer);
                    System.out.println("服务端响应数据:" + new String(readBuffer.array()));
                    selectionKey.interestOps(SelectionKey.OP_WRITE);
                }
                iterator.remove();
            }

        }



    }

}
